<?php

namespace App\Listeners;

use App\Events\WeChatNoticeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class WeChatNoticeListeners
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  MachineState  $event
     * @return void
     */
    public function handle(WeChatNoticeEvent $event)
    {   
        $wx_open_id = $event->wx_open_id;
        $message = $event->message;
        if($wx_open_id && $message){
            $info = Redis::get('wechat:token');
            Log::info('redis_info',[$info]);
            if(!$info){
                $redirect_uri = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.env('APPID').'&secret='.env('APPSECRET');
                $token_info = json_decode(file_get_contents($redirect_uri),true);
                if(isset($token_info['access_token'])){
                    $info = json_encode($token_info);
                    Redis::set('wechat:token', $info, 7000);
                }
            }
            if($info){
                $message = urlencode($message);
                $info = json_decode($info,true);
                Log::info('access_token_test111',[$info, $info['access_token']]);
                $remote_server = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$info['access_token'];
                $post_string['touser'] = $wx_open_id;
                $post_string['msgtype'] = 'text';
                $post_string['text'] = ['content'=>$message];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $remote_server);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_POSTFIELDS,urldecode(json_encode($post_string)));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $data = curl_exec($ch);
                curl_close($ch); 
            }
        }               
    }
}
